import type { UseFetchOptions } from "nuxt/app";

type Methods = "GET" | "POST" | "DELETE" | "PUT";

export interface IResultData<T> {
  code: number;
  data: T;
  msg: string;
}
export const useFetchData = () => {
  const BASE_URL = "http://blog.zaomeng.site:8080/";
  const request = <T>(
    url: string,
    method: Methods,
    data: any,
    options?: UseFetchOptions<T>
  ) => {
    const newOptions: UseFetchOptions<T> = {
      baseURL: BASE_URL,
      method: method,
      ...options,
    };

    if (method === "GET" || method === "DELETE") {
      newOptions.params = data;
    }
    if (method === "POST" || method === "PUT") {
      newOptions.body = data;
    }

    const response = useFetch(url, newOptions);
    return response;
  };
  const post = <T, K = ResponseDate<any>>(
    url: string,
    data: T,
    options?: UseFetchOptions<ResponseDate<K>>
  ) => {
    return request(url, "POST", data, options);
  };
  const get = <T, K = ResponseDate<any>>(
    url: string,
    params?: T,
    options?: UseFetchOptions<ResponseDate<K>>
  ) => {
    return request(url, "GET", params, options);
  };
  return {
    get,
    post,
  };
};
